package com.dfbz.dao.baseDao;

import com.dfbz.model.User;
import com.dfbz.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BaseDao<T> {
    private Class<T> aClass;
    public List<T> findByCol(String key, String value){
        String sql="select * from user where "+key+"=?";
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<T> list=new ArrayList<>();
        try {
            list=qr.query(sql,new BeanListHandler<>(aClass),value);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<T> findByCols(String condition, Map<String,Object> map){
        StringBuilder sb=new StringBuilder();
        sb.append("select * from user where");
        if (map.isEmpty()){
            sb.delete(sb.lastIndexOf("where"),sb.length());
        }else {
            Set<String> keySet=map.keySet();
            for (String key:keySet){
                sb.append(key).append("='").append(map.get(key)).append("' ").append(condition).append(" ");
            }
            sb.delete(sb.lastIndexOf(condition),sb.length());
        }
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<T> list=new ArrayList<>();
        try {
            list=qr.query(sb.toString(),new BeanListHandler<>(aClass));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
